#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import smtplib
from re import search
from os.path import dirname, join, isfile
from sys import argv
from sys import exit
import string
from email.mime.text import MIMEText

security_systems = ['simple', 'tls']

class message:
    def __init__(self):
        self._directory = dirname(argv[0])
        try:
            with open(join(self._directory, 'params.ini')) as params_file:
                import_ok = 0
                for line in params_file:
                    if search('^\[mail\]$', line):
                        import_ok = 1
                    elif search('^\[.*\]$', line):
                        import_ok = 0
                    elif line[0] == '#':
                        pass
                    elif import_ok == 1:
                        exec(line)
        except:
            print('Unable to locate config file "params.ini".')
            exit()
        try:
            self._server = smtp_host
        except:
            print('No SMPT server defined in params.ini.')
            exit()
        try:
            self._port = smtp_port
        except:
            print('No port defined in params.ini, 25 will be used by default.')
            self._port = '25'
        try:
            self._sender = smtp_from
        except:
            print('No sender defined in params.ini, test@domain.org will be used by default.')
            self._sender = 'test@domain.org'
        try:
            self._recipient = smtp_to
        except:
            print('Error : No recipient defined in params.ini.')
            exit()
        try:
            self._security = smtp_security
            if not self._security in security_systems:
                print('Error :', self._security, 'is not a supported security system.')
                print('Supported security systems are', " ".join(security_systems[:-1]), 'and', security_systems[-1] + '.')
                exit()
        except:
            print('smtp_security is not defined, it will be disabled except if a user is set.')
            self._security = 'disabled'
        try:
            self._login = smtp_user
            try:
                self._password = smtp_pass
            except:
                if hasattr(self, '_login'):
                    print('Error : If smtp_user is set, you must define a password with smtp_pass.')
                    exit()
            if hasattr(self, '_security') and self._security == 'disabled':
                print('smtp_user is set, smtp_security will be set to simple.')
                self._security = 'simple'
        except:
            if hasattr(self, '_security'):
                if self._security != 'disabled':
                    print('Error : If smtp_security is set to', " ".join(security_systems[:-1]), 'or', security_systems[-1], 'you must define a user and a password.')
                    exit()

    def send(self, subject, body):
        mail = MIMEText(body)
        mail.set_charset('utf-8')
        mail['From'] = self._sender
        mail['To'] = self._recipient
        mail['Subject'] = subject
        try:
            smtp = smtplib.SMTP(self._server, self._port)
        except:
            print('Unable to connect to', self._server, 'on port', self._port + '.')
            exit()
        if hasattr(self, '_security') and self._security != 'disabled':
            if self._security == 'tls':
                try:
                    smtp.set_debuglevel(1)
                    smtp.ehlo()
                    smtp.starttls()
                except:
                    print('StartTLS failed on', self._server + '.')
                    exit()
            try:
                smtp.ehlo()
                smtp.login(self._login, self._password)
            except:
                print('Authentication failed on', self._server + '.')
                exit()
        smtp.sendmail(self._sender, self._recipient.split(), mail.as_string())
        smtp.quit()

class OutOfSpace(message):
    pass

class OutOfMemory(message):
    pass

class CpuOverload(message):
    pass

class MysqlIsDown(message):
    pass

class ApacheIsDown(message):
    pass

class FtpdIsDown(message):
    pass

class SambaUnreachable(message):
    pass

class FtpUnreachable(message):
    pass

class DiskSmartError(message):
    pass

if __name__ == '__main__':
    try:
        if argv[1]:
            if isfile(argv[1]):
                body_file = []
                with open(argv[1]) as file:
                    for line in file:
                        try:
                            line.decode('UTF-8')
                        except:
                            line.decode('ISO-8859-15')
                        body_file.append(line)
                    body = ''.join(body_file)
            else:
                body = argv[1]
            try:
                if argv[2]:
                    subject = argv[2]
            except:
                subject = '--'
    except:
        subject = 'test_subject'
        body = 'test_body'
    test = message()
    message.send(test, subject, body)